<template>
  <div class="app-container">



    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item class="" label="管辖区域" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入管辖区域" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item class="" label="区域代码" prop="areaId">
        <el-input v-model="queryParams.areaId" placeholder="请输入区域代码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item class="" label="邮政编码" prop="postalCode">
        <el-input v-model="queryParams.postalCode" placeholder="请输入区域代码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="Download" @click="handleExport">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="" icon="chatSquare" @click="handleNote">日志</el-button>
      </el-col>
    </el-row>

    <!-- 
            :checkbox-config="{
          showHeader:true,
          labelField:'province',
          checkField:'province',
          indeterminateField:'province'
        }" -->
    <vxe-table :loading="loading" border="inner" :tree-config="{rowField: 'areaId',childrenField: 'children'}" highlight :data="menuList">
      <vxe-column type="checkbox" title=""  width="55"></vxe-column>
      <vxe-column field="province" title="管辖省" align="center" tree-node></vxe-column>
      <vxe-column field="city" title="管辖市" align="center"></vxe-column>
      <vxe-column field="district" title="管辖区" align="center"></vxe-column>
      <vxe-column field="areaId" title="区划代码"></vxe-column>
      <vxe-column field="postalCode" title="邮政编码"></vxe-column>
      <!-- <vxe-column field="postalCode" title="邮政编码"></vxe-column> -->
      <vxe-column field="createTime" title="创建时间"></vxe-column>
      <vxe-column field="status" title="状态">
        <template #default="scope">
          <dict-tag :options="[
            {
              label: '启用',
              value: true,
            },
            {
              label: '停用',
              value: false,
            }
          ]" :value="scope.row.status" />
        </template>
      </vxe-column>

      <vxe-column field="updateUserName" title="操作人员"></vxe-column>



      <vxe-column title="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Plus" @click="handleAddd(scope.row)">新增</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </vxe-column>
    </vxe-table>





    <!-- 添加或修改行业对话框 -->

    <el-dialog :title="title" v-model="open" width="820px" append-to-body>
      <el-form ref="menuRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="省市区" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域代码" prop="areaId">
              <el-input :disabled="handleType == '3' ? true : false" v-model="form.areaId" placeholder="请输入行政区划代码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮政编码" prop="postalCode">
              <el-input v-model="form.postalCode" placeholder="请输入邮政编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" prop="status">
              <el-select class="" clearable v-model="form.status">
                <el-option class="flex-1" v-for="item in [
                  {
                    label: '启用',
                    value: true,
                  },
                  {
                    label: '停用',
                    value: false,
                  }
                ]" :key="item.key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Menu">
import { listArea, areaAdd, updateArea, delArea } from "@/api/backArea/backArea.js";
import SvgIcon from "@/components/SvgIcon";
import IconSelect from "@/components/IconSelect";

const { proxy } = getCurrentInstance();
const { sys_show_hide, sys_normal_disable } = proxy.useDict("sys_show_hide", "sys_normal_disable");

const menuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const menuOptions = ref([]);
const isExpandAll = ref(false);
const refreshTable = ref(true);
const iconSelectRef = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    name: undefined,
    areaId: undefined,
    postalCode: undefined,
  },
  rules: {
    // menuName: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
    // orderNum: [{ required: true, message: "菜单顺序不能为空", trigger: "blur" }],
    // path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }]
  },
});

const { queryParams, form, rules } = toRefs(data);

const router = useRouter()
const route = useRoute()
const handleNote = () => {
  let menuId = route.meta.menuId
  router.push(`/system/log/operlog?data=${menuId}`)
}

/** 查询菜单列表 */
function getList() {
  loading.value = true;
  /* queryParams.value */
  listArea(queryParams.value).then(response => {
    //  menuList.value = proxy.handleTree(response, "areaId");
    menuList.value = response
    loading.value = false;
  });
}

/** 查询菜单下拉树结构 */
function getTreeselect() {
  menuOptions.value = [];
  listArea().then(response => {
    const menu = { areaId: 0, menuName: "主类目", children: [] };
    menu.children = proxy.handleTree(response, "areaId");
    menuOptions.value.push(menu);
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    "areaId": "",
    "name": "",
    "parentId": ""
  };
  proxy.resetForm("menuRef");
}

// 判断是父新增 还是 子新增 还是修改
const handleType = ref("1")


/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset();
}

/** 选择图标 */
function selected(name) {
  form.value.icon = name;
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();

}


/** 新增按钮操作 */
function handleAddd(row) {
  console.log(row, "row");
  handleType.value = '2'
  reset();
  open.value = true;
  title.value = "添加地区";
  // delete form.value.parentId
  form.value.parentId = row.areaId;
}

/** 新增按钮操作 */
function handleAdd(row) {
  console.log('handleAdd');
  handleType.value = '1'

  reset();
  open.value = true;
  title.value = "添加地区";
  form.value.areaId = row.areaId;
  form.value.parentId = row.parentId;

  console.log('form.value.areaId', form.value.areaId);


  return;
  reset();
  getTreeselect();
  if (row != null && row.areaId) {
    form.value.parentId = row.areaId;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加菜单";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  handleType.value = '3'
  reset();
  // form.value.areaId = row.areaId;
  form.value.parentId = row.areaId;
  form.value.name = row.name;
  form.value.areaId = row.areaId;
  open.value = true;
  title.value = "修改菜单";

  // getMenu(row.areaId).then(response => {
  //   form.value = response;
  //   open.value = true;
  //   title.value = "修改菜单";
  // });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["menuRef"].validate(valid => {
    if (valid) {

      if (handleType.value == '1') {
        areaAdd(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      } else if (handleType.value == '2') {
        areaAdd(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      } else if (handleType.value == '3') {
        updateArea(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      }

    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项?').then(function () {
    return delArea(row.areaId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {

  console.log(queryParams.value,'queryParams.value');
  return
  proxy.download(
    "/backAdmin/areaApi/export",
    {
      ...queryParams.value,
    },
    `user_${new Date().getTime()}.xlsx`
  );
}



// 树结构获取数据
function load(tree, treeNode, resolve) {
  // 查找子节点数据
  function findNodeById(node, id) {
    // 找到对应id数据
    if (node.id === id) {
      // 拷贝当前节点数据
      const newNode = { ...node };
      if (newNode.children && newNode.children.length > 0) {
        // 修改查找到的对应id的children数据，把找到的数据里面的children数据置空，并设置hasChildren
        newNode.children = newNode.children.map(child => {
          return {
            ...child,
            // 设置hasChildren判断是否显示展开按钮
            hasChildren: child.children.length > 0 ? true : false,
            children: []  // 置空子节点
          };
        });
      }
      return newNode.children;
    }
    // 递归查找每一层的children数据
    if (node.children && node.children.length > 0) {
      for (let i = 0; i < node.children.length; i++) {
        const result = findNodeById(node.children[i], id);
        if (result) {
          return result;
        }
      }
    }
    return null;
  }
  const foundNode = findNodeById(this.listCopy[0], tree.id);
  //设置map值，记录当前展开的值，方便后期新增/修改对应行值时修改数据
  this.maps.set(tree.id, { tree, treeNode, resolve })
  resolve(foundNode)
}
getList();
</script>